package org.jeecg.modules.cascv.image.service.merge.shengwushiyangui;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.HexUtil;
import com.NativeImageIO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.service.merge.ranshaogui.Ranshaogui2Service;
import org.jeecg.modules.cascv.image.util.HeaderUtil;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.jeecg.modules.cascv.image.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author贺弘烨
 * @Version 2022/3/21
 * description;
 */
@Service
@Slf4j
public class ShengwushiyanguiJ2kService extends ImageService {
    @Value("${imageurl}")
    private String imageurl;

    @Autowired
    private TaskExecutePool taskExecutePool;

    @Override
    public String idsNames() {
        return "6D2DH_51H,6D4DH_51H,6D6DH_51H,6D8DH_51H,6D2DH_57H,6D2DH_5AH";
    }


    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {
        JSONObject conJson = jsonObject.getJSONObject("Content");

        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        //log.info("包序号："+intpackageNum);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if (null == lastPackageNum) {
            LaptopConstant.packageNumMap.put(key, intpackageNum);
        } else {
            LaptopConstant.packageNumMap.put(key, intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:" + intpackageNum + "，上一包包序号:" + lastPackageNum);
                }
            }
        }
        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subSecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);
        String frames_field = LaptopConstant.FRAME_FIELD_MAP.get(idsName);
        String dataFrames = conJson.getString(frames_field);
        //dataFrames = dataFrames.substring(7, dataFrames.length() - 10);
        dataFrames = dataFrames.split(";")[1].substring(2).trim();
        String xAxis = conJson.getString(LaptopConstant.XAxis_MAP.get(idsName)).split(";")[0].substring(2);
        String yAxis = conJson.getString(LaptopConstant.YAxis_MAP.get(idsName)).split(";")[0].substring(2);;
        String zAxis = conJson.getString(LaptopConstant.ZAxis_MAP.get(idsName)).split(";")[0].substring(2);;
        String integralTime = conJson.getString(LaptopConstant.IntegralTime_MAP.get(idsName)).split(";")[0].substring(2);;
        String xyztime =xAxis+yAxis+zAxis+integralTime;
        dataFrames = xyztime+dataFrames;
        StringBuilder queue = LaptopConstant.imageData.get(key);
        //判断queue是否有数据 并且queue长度小于2006*2
        if (queue != null && queue.length() < 2006 * 2) { //ququ不是空切长度不小于2006*2
            dataFrames = queue.toString() + dataFrames;
            boolean checkStart = false;
            if (StringUtils.containsIgnoreCase(dataFrames, LaptopConstant.SHENGWUSHIYANGUI_J2K_HEADER)) { //表示是否包含fffffff0
                checkStart = true;
            }

            if (checkStart) { //如果为true
                queue = new StringBuilder();//new一个queue存入imageData
                LaptopConstant.imageData.put(key, queue);
                queue.append(dataFrames); //queue添加dataFrames

            } else {//如果是假的 那么将这个key删除掉  dataFrams不包含"fffffff0"
                LaptopConstant.imageData.remove(key);
            }
            return null;
        }
//判断是否包含fffffff0
        if (StringUtils.containsIgnoreCase(dataFrames, LaptopConstant.SHENGWUSHIYANGUI_J2K_HEADER)) {
            if (queue != null) { //queue有数据
                queue.append(dataFrames); //queue加上dataFrames
                if (queue.length() > 2006 * 2) { //如果queue的长度是大于2006*2的 那么去合并
                    composite(queue, conJson, idsName, key, secondStr, subSecondStr);
                }
            }
            //创建一个queue
            queue = new StringBuilder();
            //存入imageData
            LaptopConstant.imageData.put(key, queue);
            //queue再添加dataFrames  dataFrames:是已被queue加上的之后的了  dataFrames = queue.toString() + dataFrames;
            queue.append(dataFrames); //然后把刚才new的queue再加上dataFrames

            return null;
        }
        //判断是否是截断数据
        if (isNeedMergeBehindXuanFu(dataFrames) && queue == null) {//判断dataFrames是否有结尾，并且queue不是空的
            queue = new StringBuilder();
            LaptopConstant.imageData.put(key, queue);
            //Java中的append( )方法其实是创建了一个新的数组，扩大了长度，将需要添加的字符串给复制到这个新的数组中
            //Stringbuffer是动态字符串数组，append( )是往动态字符串数组添加，跟“xxxx”+“yyyy”相当‘+’号
            queue.append(dataFrames);

            return null;
        } else if (queue != null) { //如果queue不是空的那么加上dataFrames
            queue.append(dataFrames);
            return null;
        }

        return null;
    }


    private boolean composite(StringBuilder sb, JSONObject content, String idsName, String key, String secondStr, String subSecondStr) {
        int width = 1024;
        int height = 1024;


        String imgHexStr = sb.toString();
        int headerIndex = StringUtils.indexOfIgnoreCase(imgHexStr, LaptopConstant.SHENGWUSHIYANGUI_J2K_HEADER);
        sb.delete(0, headerIndex + 32);
        imgHexStr = sb.toString();
        int headerIndex2 = StringUtils.indexOfIgnoreCase(imgHexStr, LaptopConstant.SHENGWUSHIYANGUI_J2K_HEADER);
        String substring = sb.substring(0, headerIndex2);

        CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
            long start = System.currentTimeMillis();
            byte[] bytes = HexUtil.decodeHex(substring);
            String idStr = IdWorker.getIdStr();
            idStr = idStr + ".jpeg";
            //  int png = LaptopConstant.nativeImageIO.write(bytes, 500, 500, "/data/", idStr + ".png", "png");
            FileUtil.touch("/data/images/" + idStr);

            ByteArrayInputStream byteArrayInputStream = null;
            ImageInputStream imageInputstream = null;
            try {
                byteArrayInputStream = new ByteArrayInputStream(bytes);
                imageInputstream = new MemoryCacheImageInputStream(byteArrayInputStream);
                BufferedImage read = ImageIO.read(imageInputstream);

                ImageIO.write(read, "jpeg", new File("/data/images/" + idStr));
            } catch (Exception e) {
                log.error("生物技术实验柜j2k," + e);
            }
//                finally {
//
//                    try {
//                        byteArrayInputStream.close();
//                        imageInputstream.close();
//                    } catch (IOException e) {
//                        log.error("生物技术实验柜j2k流关闭错误," + e);
//                    }
//                }
            String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr;
            System.out.println("imageUrl = " + imageUrl);
            content.put("imageUrl", imageUrl);
            content.put("idsName", idsName);
            //   String secondStr = content.getString(LaptopConstant.SECOND_FIELD_MAP.get(idsName)).split(";")[1];
            //  String subSecondStr = content.getString(LaptopConstant.SUB_SECOND_FIELD_MAP.get(idsName)).split(";")[1];
            String[] split = secondStr.split(":");
            content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
            content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
            List<JSONObject> jsonObjectList = new CopyOnWriteArrayList<>();
            jsonObjectList.add(content);
            content.put("key", key);
            log.info("生物技术实验柜"+idsName+"合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");

            return content;
        }, taskExecutePool.threadPoolTaskExecutor2());
        LaptopConstant.imageFutureList.add(future);

        LaptopConstant.imageData.remove(key);//清空图片数据


        return true;
    }

    private boolean isNeedMergeBehindXuanFu(String dataFrames) {
        return StringUtils.endsWithIgnoreCase(dataFrames, LaptopConstant.SHENGWUSHIYANGUI_J2K_HEADER_SUB_1) //后缀均可以通过endsWith()方法来判断 是的返回true
                || StringUtils.endsWithIgnoreCase(dataFrames, LaptopConstant.SHENGWUSHIYANGUI_J2K_HEADER_SUB_2)
                || StringUtils.endsWithIgnoreCase(dataFrames, LaptopConstant.SHENGWUSHIYANGUI_J2K_HEADER_SUB_3)
                ;
    }

    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");  //D:\pc_workspace\shengwushiyan2\
        List<String> strings = FileUtil.readUtf8Lines("D:\\pc_workspace\\生物技术实验柜0901\\J2K\\TGWTYY0901_094H_31_BTRAPP2.txt");
        ShengwushiyanguiJ2kService shengwushiyanguiJ2kService = new ShengwushiyanguiJ2kService();
        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);//TGWTYY0901_094H_31_BTRAPP2
            shengwushiyanguiJ2kService.merge(jsonObject, "TGWTYY0901_094H_31_BTRAPP2", "TGWTYY0901_094H_31_BTRAPP2");
        }

//        byte[] bytes = HexUtil.decodeHex(FileUtil.readUtf8String("E:\\11图像数据\\cut\\生命生态\\bytes2.txt"));
//
//     //   FileUtil.writeBytes(bytes, "/data/images/j2k"+System.currentTimeMillis()+".jpeg");
//       ByteArrayInputStream byteArrayInputStream = null;
//        ImageInputStream imageInputstream = null;
//        try {
//            byteArrayInputStream = new ByteArrayInputStream(bytes);
//            imageInputstream = new MemoryCacheImageInputStream(byteArrayInputStream);
//            BufferedImage read = ImageIO.read(imageInputstream);
//
//            ImageIO.write(read, "jpeg", new File("/data/images/j2k"+System.currentTimeMillis()+".jpeg"));
//        } catch (Exception e) {
//            log.error("生物技术实验柜j2k," + e);
//        } finally {
//            try {
//                byteArrayInputStream.close();
//                imageInputstream.close();
//            } catch (Exception e) {
//                log.error("生物技术实验柜j2k流关闭错误," + e);
//            }
//        }

    }

}
